<?php


namespace app\admin\service\base;


use app\admin\model\base\PaperSubject;
use app\admin\model\base\PaperSubject as Question;
use app\admin\model\base\StudentPaper;
use app\admin\model\base\Subject;
use app\admin\model\StudentPractise;
use app\admin\validates\PaperSubjectValidate;
use app\BaseService;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class PaperSubjectService extends BaseService
{
    /**
     * 列表
     * @param array $params
     * @return Json
     */
    public function index(array $params): Json
    {
        $where = ['is_del'=>0];
        //获取列表
        $data = Question::getList($where, $params['page'] ?? 1, $params['limit'] ?? 100, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 详情
     * @param array $params
     * @return Json
     */
    public function read(array $params): Json
    {
        $where = ['id'=>$params['id']];
        $data = Question::where($where)->with(['subjects','question_cates'])->find();
        return jsonReturn(1, $data);
    }

    /**
     * 保存
     * @param array $params
     * @return Json
     */
    public function save(array $params): Json
    {
        //数据验证
        try {
            validate(PaperSubjectValidate::class)->scene('create')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }

        $list = $params['list'];
        Db::startTrans();
        try {
            $arr = Subject::types();
            $PaperSubject = new PaperSubject();
            $dataUpdate = [];
            if(!empty($list)){
                foreach ($list as $value){
                    $count = StudentPaper::where('paper_id','=',$value['paper_id'])->count();
                    if($count > 0){
                        throw new \Exception('已有学生参加考试，不允许加题!');
                    }
                    //处理答案
                    if($value['type'] == 1 || $value['type'] == 2){
                        $analysis = [];
                        $content = json_decode($value['content'],true);
                        if(isset($content['list']) && !empty($content['list'])){
                            foreach ($content['list'] as $analysiss){
                                if($analysiss['is_answer'] == true){
                                    $analysis[] = $analysiss['lable'];
                                }
                            }
                        }

                        $value['analysis'] = implode(',',$analysis);
                    }
                    $datas = [
                        'title'=>$value['title'],
                        'degree'=>$value['degree'],
                        'paper_id'=>$value['paper_id'],
//                        'create_user'=>WS_ADMIN_ID,
                        'type'=>$value['type'],
                        'weighting'=>$value['weighting'] ?? 0,
                        'subject_id'=>$value['subject_id'] ?? 0,
                        'analysis'=>$value['analysis'] ?? '',
                        'analysis_desc'=>$value['analysis_desc'],
                        'lable'=>$arr[$value['type']],
                        'content'=>$value['content'],
                    ];
                    if(isset($value['id']) && $value['id'] && $value['id'] > 0){
                        $datas['id'] = $value['id'];
                    }
                    $dataUpdate[]  = $datas;
                }

                if(!empty($dataUpdate)){
                    $res = $PaperSubject->saveAll($dataUpdate);
                    if(!$res){
                        throw new \Exception('保存失败');
                    }
                }
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return jsonReturn(0, [],$exception->getMessage());
        }
        return jsonReturn(1, []);
    }

    /**
     * 编辑
     * @param array $params
     * @return Json
     */
    public function update(array $params): Json
    {
        //数据验证
        try {
            validate(PaperSubjectValidate::class)->scene('edit')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $count = StudentPaper::where('paper_id','=',$params['paper_id'])->count();
        if($count > 0){
            return jsonReturn(0, [], '已有学生参加考试，不允许编辑');
        }
        $arr = Subject::types();
        //处理答案
        if($params['type'] == 1 || $params['type'] == 2){
            $analysis = [];
            $content = json_decode($params['content'],true);
            if(isset($content['list']) && !empty($content['list'])){
                foreach ($content['list'] as $analysiss){
                    if($analysiss['is_answer'] == true){
                        $analysis[] = $analysiss['lable'];
                    }
                }
            }

            $params['analysis'] = implode(',',$analysis);
        }
        $dataUpdate = [
            'title'=>$params['title'],
            'degree'=>$params['degree'],
            'paper_id'=>$params['paper_id'],
//            'create_user'=>WS_ADMIN_ID,
            'type'=>$params['type'],
            'subject_id'=>$params['subject_id'],
            'weighting'=>$params['weighting'] ?? 0,
            'analysis'=>$params['analysis'] ?? '',
            'analysis_desc'=>$params['analysis_desc'],
            'lable'=>$arr[$params['type']],
            'content'=>$params['content'],
        ];
        $data = Question::where('id','=',$params['id'])->update($dataUpdate);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 编辑
     * @param array $params
     * @return Json
     */
    public function delete(array $params): Json
    {
        $where = [];
        //获取列表
        $data = Question::where('id','=',$params['id'])->update(['is_del'=>1]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }
}